package com.cyt.work.divideclass.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.SysFileService;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EntryUtils;
import com.cyt.sys.util.FilePathUtil;
import com.cyt.sys.util.GlobalExcelDictHandler;
import com.cyt.work.divideclass.dao.*;
import com.cyt.work.divideclass.model.po.*;
import com.cyt.work.divideclass.model.vo.*;
import com.cyt.work.divideclass.service.DivideclassGradeService;
import com.cyt.work.divideclass.service.DivideclassRuleService;
import com.cyt.work.divideclass.service.DivideclassService;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.vo.WxEducationUserImportVo;
import com.cyt.wx.model.vo.WxEducationUserVerifyImportVo;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.cyt.wx.service.WxEducationUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 智能分班-智能分班Service层实现类
 *
 * @author caideyong
 * @date 2019-12-20 13:54:04
 */
@Service("divideclassService")
public class DivideclassServiceImpl extends BaseServiceImpl<Divideclass> implements DivideclassService {

    @Resource
    private DivideclassDao divideclassDao;

    @Autowired
    public void setBaseDao(DivideclassDao divideclassDao) {
        this.baseDao = divideclassDao;
    }

    @Autowired
    private DivideclassStudentDao divideclassStudentDao;
    @Autowired
    private DivideclassRuleDao divideclassRuleDao;
    @Autowired
    private DivideclassClassDao divideclassClassDao;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private DivideclassGradeService divideclassGradeService;
    @Autowired
    private DivideclassRuleService divideclassRuleService;
    @Autowired
    private WxEducationUserService wxEducationUserService;
    @Autowired
    private DivideclassMessageDao divideclassMessageDao;


    private static final String MALE = "1";
    private static final String FEMALE = "2";
    private static final boolean SHOWLOG = false;
    private static final int TIME = 0;

    private static long startTime = 0L;
    private static long endTime = 0L;

    private int mStudentNum = 0;
    private boolean mXbjh = false;
    private boolean mCjjh = false;
    private boolean mZfjh = false;
    private float mZfwc = 0f;
    private boolean mDkjh = false;
    private float mDkwc = 0f;
    private boolean mScxh = false;
    private String mXhZM = null;
    private String mXhbh = null;

    private List<String> mXhList = null;
    private List<DivideclassStudentVo> mFbStudentVOList = null;
    private List<DivideclassStudentVo> mMaleFbStudentVOList = null;
    private List<DivideclassStudentVo> mFemaleFbStudentVOList = null;
    private List<DivideclassClassVo> mFbClassDividingVOList = null;

    /**
     * 查询对象集合
     *
     * @param divideclassVo 对象
     * @return List 对象集合
     * @author caideyong
     * @date 2019-12-20 13:54:04
     */
    @Override
    public List<Divideclass> listExample(DivideclassVo divideclassVo) {
        return divideclassDao.getDivideClassList(divideclassVo);
    }

    /**
     * 分页查询
     *
     * @param divideclassVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 13:54:04
     */
    @Override
    public ReturnResult page(DivideclassVo divideclassVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<Divideclass> list = listExample(divideclassVo);
        PageInfo<Divideclass> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param divideclassVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 13:54:04
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(DivideclassVo divideclassVo, SysUser sysUser) {
        if (StringUtils.isBlank(divideclassVo.getId())) {
            Divideclass divideclass = new Divideclass(sysUser);
            divideclass.setTitle(divideclassVo.getTitle());
            divideclass.setDivideType(divideclassVo.getDivideType());
            if(StringUtils.isEmpty(divideclassVo.getDivideNum())){
                divideclass.setDivideNum("0");
            }else {
                divideclass.setDivideNum(divideclassVo.getDivideNum());
            }
            divideclass.setDivideStatus("0");//待分班
            divideclass.setCreator(sysUser.getId());
            divideclass.setCreateTime(new Date());
            divideclass.setApplyId(divideclassVo.getApplyId());
            divideclassDao.insert(divideclass);
            return new ReturnResult(divideclass.getId());
        } else {
            Divideclass divideclass = divideclassDao.selectByPrimaryKey(divideclassVo.getId());
            divideclass.setTitle(divideclassVo.getTitle());
            divideclass.setDivideType(divideclassVo.getDivideType());
            divideclass.setDivideStatus("0");//待分班
            divideclass.setUpdator(sysUser.getId());
            divideclass.setUpdateTime(new Date());
            divideclassDao.updateByPrimaryKey(divideclass);
            return new ReturnResult(divideclass.getId());
        }
    }

    @Override
    public ReturnResult importData(HttpServletRequest request, MultipartFile file, String catalog, String update, String applyId, String divideId, SysUser sysUser) {
        // 1、不更新已存在数据，2、更新存在数据
        ReturnResult returnResult = sysFileService.fileUpload(file, request, catalog, BaseConstant.FILE_TYPE_EXECL);
        if (ErrorCode.CODE_0 == returnResult.getCode()) {
            String filePath = FilePathUtil.acceptCheckRealPath(request) + returnResult.getData().toString();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedVerify(true);
            // 解决多读取问题，如果出现没有导入问题，需要将该属性去除
            params.setKeyIndex(0);
            // 如果有code码需要设置，现有bug，需要修改源码CellValueService
            params.setDictHandler(new GlobalExcelDictHandler());
            ExcelImportResult<WxEducationUserVerifyImportVo> result = ExcelImportUtil.importExcelMore(new File(filePath), WxEducationUserVerifyImportVo.class, params);
            List<WxEducationUserVerifyImportVo> educationUserImportList = result.getList();
            if (CollUtil.isNotEmpty(educationUserImportList)) {
                Map<String, WxEducationUserImportVo> educationUserMap = new HashMap<>();
                String key;
                for (WxEducationUserImportVo educationUser : educationUserImportList) {
                    key = educationUser.getUserNumber();
                    if (educationUserMap.keySet().contains(key)) {
                        continue;
                    }
                    educationUserMap.put(key, educationUser);
                }
                List<WxEducationUser> wxEducationUserList = new ArrayList<>();
                for (Map.Entry<String, WxEducationUserImportVo> entry : educationUserMap.entrySet()) {
                    // 账号不存在，保存进用户表
                    WxEducationUserImportVo userFrom = entry.getValue();
                    // 查询账号是否存在
                    WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
                    wxEducationUserVo.setUserNumber(userFrom.getUserNumber());
                    List<WxEducationUser> list = wxEducationUserService.listExample(wxEducationUserVo);
                    WxEducationUser wxEducationUser;
                    if (CollUtil.isEmpty(list)) {
                        wxEducationUser = new WxEducationUser();
                        String mobile = userFrom.getMobile();
                        wxEducationUser.setId(BaseUtil.uId());
                        wxEducationUser.setApplyId(applyId);
                        wxEducationUser.setLoginName(userFrom.getUserNumber());
                        wxEducationUser.setMobile(mobile);
                        wxEducationUser.setName(userFrom.getName());
                        wxEducationUser.setUserNumber(userFrom.getUserNumber());
                        wxEducationUser.setExamine(divideId);
                        wxEducationUser.setStatus(BaseConstant.BASE_STATUS_YES);
                        if (StringUtils.isNotEmpty(mobile) && mobile.length() == 11) {
                            wxEducationUser.setPassword(MD5Util.MD5Encode(StrUtil.sub(mobile, 5, 11)));
                        } else {
                            wxEducationUser.setPassword(MD5Util.MD5Encode(BaseConstant.DEFAULT_EDUCATION_USER_PASSWORD));
                        }
                        wxEducationUser.setUserType(userFrom.getUserType());
                        wxEducationUser.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                        wxEducationUser.setCreateUser(sysUser.getId());
                        wxEducationUser.setUpdateUser(sysUser.getId());
                        wxEducationUser.setCreateTime(cn.hutool.core.date.DateUtil.date());
                        wxEducationUser.setUpdateTime(cn.hutool.core.date.DateUtil.date());
                        wxEducationUserList.add(wxEducationUser);
                    } else {
                        if (StringUtils.equals(update, BaseConstant.IMPORT_STATUS_UPDATE_NO)) {
                            continue;
                        }
                        // 直接更新
                        wxEducationUser = list.get(0);
                        boolean flag = wxEducationUserService.checkUserNumberUnique(wxEducationUser.getId(), userFrom.getUserNumber(), sysUser.getId());
                        // false表示可以使用
                        if (!flag) {
                            wxEducationUser.setLoginName(userFrom.getUserNumber());
                            wxEducationUser.setMobile(userFrom.getMobile());
                            wxEducationUser.setName(userFrom.getName());
                            wxEducationUser.setExamine(divideId);
                            wxEducationUser.setApplyId(applyId);
                            wxEducationUser.setUserNumber(userFrom.getUserNumber());
                            wxEducationUser.setUserType(userFrom.getUserType());
                            wxEducationUser.setUpdateUser(sysUser.getId());
                            wxEducationUser.setUpdateTime(new Date());
                            wxEducationUserService.updateByPrimaryKey(wxEducationUser);
                        }
                    }
                }
                // 保存
                if (wxEducationUserList != null && wxEducationUserList.size() > 0) {
                    wxEducationUserService.insertList(wxEducationUserList);
                }
            }
            // 行号从0开始，要加上titleRows和headRows
            if (result.isVerfiyFail()) {
                // 如果错误，打印出提醒，直接返回
                int successNum = 0;
                int failNum = result.getFailList().size();
                if (result.getList() != null && result.getList().size() > 0) {
                    successNum = result.getList().size();
                }
                String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
                List<WxEducationUserVerifyImportVo> failList = result.getFailList();
                return new ReturnResult(ErrorCode.CODE_1, failList, errorMsg);
            }
        }
        return returnResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult fbResult(DivideclassVo divideclassVo, SysUser sysUser) {
        //根据divideId查询此次分班的人
        WxEducationUserVo wxEducationUserVo=new WxEducationUserVo();
        wxEducationUserVo.setExamine(divideclassVo.getId());
        wxEducationUserVo.setUserType("3");//学生
        //学生
        DivideclassStudentVo divideclassStudentVo=new DivideclassStudentVo();
        divideclassStudentVo.setDivideId(divideclassVo.getId());
        List<DivideclassStudent> divideclassStudentList=divideclassStudentDao.getDivideclassStudentResultList(divideclassStudentVo);
        List<DivideclassMessage> divideclassMessageList=new ArrayList<>();
        if(divideclassStudentList!=null&&divideclassStudentList.size()>0){
            for(DivideclassStudent d:divideclassStudentList){
                DivideclassMessage divideclassMessage=new DivideclassMessage();
                divideclassMessage.setId(BaseUtil.uId());
                divideclassMessage.setName("分班结果通知");
                divideclassMessage.setClassId(d.getClassId());
                DivideclassClassVo divideclassClassVo=new DivideclassClassVo();
                divideclassClassVo.setId(d.getClassId());
                List<DivideclassClass> divideclassClassList=divideclassClassDao.getDivideclassClassListNew(divideclassClassVo);
                if(divideclassClassList!=null&&divideclassClassList.size()>0){
                    divideclassMessage.setClassName(divideclassClassList.get(0).getName());
                    divideclassMessage.setClassNum(divideclassClassList.get(0).getNum());
                    divideclassMessage.setHeadTeacher(divideclassClassList.get(0).getHeadTeacherName());
                }
                divideclassMessage.setDivideId(divideclassVo.getId());
                divideclassMessage.setType("0");
                divideclassMessage.setUserId(d.getEduUser());
                divideclassMessage.setCreateTime(new Date());
                divideclassMessage.setCreator(sysUser.getId());
                divideclassMessage.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                divideclassMessageList.add(divideclassMessage);
            }
            //教师
            DivideclassClassVo divideclassClassVo=new DivideclassClassVo();
            divideclassClassVo.setDivideId(divideclassVo.getId());
            List<DivideclassClass> divideclassClassList=divideclassClassDao.getDivideclassClassListNew(divideclassClassVo);
            if(divideclassClassList!=null&&divideclassClassList.size()>0){
                for(DivideclassClass d:divideclassClassList){
                    DivideclassMessage divideclassMessage=new DivideclassMessage();
                    divideclassMessage.setId(BaseUtil.uId());
                    divideclassMessage.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                    divideclassMessage.setCreator(sysUser.getId());
                    divideclassMessage.setCreateTime(new Date());
                    divideclassMessage.setUserId(d.getHeadTeacher());
                    divideclassMessage.setType("1");
                    divideclassMessage.setHeadTeacher(d.getHeadTeacherName());
                    divideclassMessage.setDivideId(divideclassVo.getId());
                    divideclassMessage.setClassNum(d.getNum());
                    divideclassMessage.setClassName(d.getName());
                    divideclassMessage.setClassId(d.getId());
                    divideclassMessage.setName(d.getName());
                    divideclassMessageList.add(divideclassMessage);
                }
            }
            divideclassMessageDao.insertList(divideclassMessageList);
            Divideclass divideclass=divideclassDao.selectByPrimaryKey(divideclassVo.getId());
            divideclass.setResultStatus("1");
            divideclassDao.updateByPrimaryKey(divideclass);
            return new ReturnResult(ErrorCode.CODE_0,"发布成功！");
        }else{
            return new ReturnResult(ErrorCode.CODE_1,"分班用户不存在,请导入分班用户！");
        }
    }

    /**
     * 开始分班
     * @author caideyong
     * @date 2020/1/3
     * @param divideclassVo 传入参数对象
     * @param sysUser 用户信息
     * @return ReturnResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult divideClass(DivideclassVo divideclassVo, SysUser sysUser) {
        if (sysUser != null && sysUser.getId() != null) {
            ReturnResult r = prepareData(divideclassVo.getId());
            if (r.getCode()==0) {
                if (classDividingArithmetic()) {
                    saveClassDividingResult(sysUser);
                    //分好班了修改此次分班状态
                    Divideclass divideclass=divideclassDao.selectByPrimaryKey(divideclassVo.getId());
                    divideclass.setDivideStatus("1");//已分班
                    divideclass.setResultStatus("0");//待发布
                    divideclassDao.updateByPrimaryKey(divideclass);
                } else {
                    return new ReturnResult(ErrorCode.CODE_1,"请减少班级数量，或增大均分误差！");
                }
            } else {
                return new ReturnResult(ErrorCode.CODE_1,r.getMsg());
            }
            return new ReturnResult(ErrorCode.CODE_0,"分班成功！");
        }
        return null;
    }

    @Override
    public ReturnResult importExcel(HttpServletRequest request, MultipartFile file, String catalog, SysUser sysUser, String divideId, String applyId) {
        ReturnResult returnResult = sysFileService.fileUpload(file, request, catalog, BaseConstant.FILE_TYPE_EXECL);
        if (ErrorCode.CODE_0 == returnResult.getCode()) {
            String filePath = FilePathUtil.acceptCheckRealPath(request) + returnResult.getData().toString();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedVerify(true);
            // 解决多读取问题，如果出现没有导入问题，需要将该属性去除
            params.setKeyIndex(0);
            // 如果有code码需要设置，现有bug，需要修改源码CellValueService
            params.setDictHandler(new GlobalExcelDictHandler());
            ExcelImportResult<DivideclassStudentGradeVerifyImportVo> result = ExcelImportUtil.importExcelMore(new File(filePath), DivideclassStudentGradeVerifyImportVo.class, params);
            List<DivideclassStudentGradeVerifyImportVo> educationUserImportList = result.getList();
            if (CollUtil.isNotEmpty(educationUserImportList)) {
                //先删除已有的数据
                DivideclassGradeVo e = new DivideclassGradeVo();
                e.setDivideId(divideId);
                divideclassGradeService.delete(e, sysUser);
                Map<String, DivideclassStudentGradeImportVo> educationUserMap = new HashMap<>();
                String key;
                for (DivideclassStudentGradeImportVo educationUser : educationUserImportList) {
                    key = educationUser.getXh();
                    if (educationUserMap.keySet().contains(key)) {
                        continue;
                    }
                    educationUserMap.put(key, educationUser);
                }
                List<DivideclassGrade> divideclassGradeList = new ArrayList<>();
                for (Map.Entry<String, DivideclassStudentGradeImportVo> entry : educationUserMap.entrySet()) {
                    // 名称不存在
                    DivideclassStudentGradeImportVo userFrom = entry.getValue();
                    DivideclassGrade divideclassGrade = new DivideclassGrade();
                    divideclassGrade.setId(BaseUtil.uId());
                    divideclassGrade.setDivideId(divideId);
                    divideclassGrade.setName(userFrom.getName());
                    divideclassGrade.setXh(userFrom.getXh());
                    divideclassGrade.setChinese(userFrom.getChinese());
                    divideclassGrade.setBiological(userFrom.getBiological());
                    divideclassGrade.setChemistry(userFrom.getChemistry());
                    divideclassGrade.setEnglish(userFrom.getEnglish());
                    divideclassGrade.setGeography(userFrom.getGeography());
                    divideclassGrade.setHistory(userFrom.getHistory());
                    divideclassGrade.setMath(userFrom.getMath());
                    divideclassGrade.setPhysical(userFrom.getPhysical());
                    divideclassGrade.setPolitical(userFrom.getPolitical());
                    divideclassGrade.setTotal(userFrom.getTotal());
                    divideclassGradeList.add(divideclassGrade);
                }
                // 保存
                if (divideclassGradeList != null && divideclassGradeList.size() > 0) {
                    divideclassGradeService.insertList(divideclassGradeList);
                    //修改学生总分成绩
                    DivideclassStudentVo divideclassStudentVo=new DivideclassStudentVo();
                    divideclassStudentVo.setDivideId(divideId);
                    divideclassStudentDao.updateScore(divideclassStudentVo);
                }
            } else {
                // 行号从0开始，要加上titleRows和headRows
                if (result.isVerfiyFail()) {
                    // 如果错误，打印出提醒，直接返回
                    int successNum = 0;
                    int failNum = result.getFailList().size();
                    if (result.getList() != null && result.getList().size() > 0) {
                        successNum = result.getList().size();
                    }
                    String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
                    List<DivideclassStudentGradeVerifyImportVo> failList = result.getFailList();
                    return new ReturnResult(ErrorCode.CODE_1, failList, errorMsg);
                }
            }
        }
        return returnResult; // 1、不更新已存在数据，2、更新存在数据
    }

    private boolean classDividingArithmetic() {
        startTime = System.currentTimeMillis();
        if (mZfjh) {
            float totalScore = 0f;
            for (int i = 0; i < mFbStudentVOList.size(); i++) {
                totalScore += Float.parseFloat(mFbStudentVOList.get(i).getTotalScore());//导入成绩
            }
            float averageScore = (totalScore / mFbStudentVOList.size());//总均分

            //每班随机一个最高分
            int maleIsNull = 0;//全是男生
            int femaleIsNull = 0;//全是女生
            int maleAndFemaleNotNull = 0;//有男有女
            for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                int male = Integer.parseInt(divideclassClassVo.getBnum());//男生人数
                int female = Integer.parseInt(divideclassClassVo.getGnum());//女生人数
                //判断男生，女生是否为0
                if (male != 0 && female == 0) {
                    maleIsNull++;
                } else if (male == 0 && female != 0) {
                    femaleIsNull++;
                } else if (male != 0 && female != 0) {
                    maleAndFemaleNotNull++;
                }
            }

            Random rand = new Random();
            //全是男生
            if (maleIsNull != 0) {
                for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                    DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                    int male = Integer.parseInt(divideclassClassVo.getBnum());
                    int female = Integer.parseInt(divideclassClassVo.getGnum());
                    if (male != 0 && female == 0) {
                        int index = rand.nextInt(maleIsNull);
                        DivideclassStudentVo divideclassStudentVo = mMaleFbStudentVOList.get(index);
                        List<DivideclassStudentVo> divideclassStudentVoList = new ArrayList<>();
                        divideclassStudentVoList.add(divideclassStudentVo);
                        divideclassClassVo.setMaleList(divideclassStudentVoList);
                        int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                        int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                        //新的总均分
                        float newAverageScore = (Float.parseFloat(divideclassClassVo.getAverage()) * (maleSize + femaleSize - 1) + Float.parseFloat(divideclassStudentVo.getTotalScore())) * 100 / (maleSize + femaleSize) / 100;
                        divideclassClassVo.setAverage(String.valueOf(newAverageScore));
                        maleIsNull--;
                        mMaleFbStudentVOList.remove(index);
                        for (int j = 0; j < mFbStudentVOList.size(); j++) {
                            if (divideclassStudentVo.getId().equals(mFbStudentVOList.get(j).getId())) {
                                mFbStudentVOList.remove(j);
                                break;
                            }
                        }
                    }
                }
            }

            if (femaleIsNull != 0) {
                for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                    DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                    int male = Integer.parseInt(divideclassClassVo.getBnum());
                    int female = Integer.parseInt(divideclassClassVo.getGnum());
                    if (male == 0 && female != 0) {
                        int index = rand.nextInt(femaleIsNull);
                        DivideclassStudentVo divideclassStudentVo = mFemaleFbStudentVOList.get(index);
                        List<DivideclassStudentVo> divideclassStudentVoList = new ArrayList<>();
                        divideclassStudentVoList.add(divideclassStudentVo);
                        divideclassClassVo.setFemaleList(divideclassStudentVoList);
                        int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                        int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                        float newAverageScore = (Float.parseFloat(divideclassClassVo.getAverage()) * (maleSize + femaleSize - 1) + Float.parseFloat(divideclassStudentVo.getTotalScore())) * 100 / (maleSize + femaleSize) / 100;
                        divideclassClassVo.setAverage(String.valueOf(newAverageScore));
                        femaleIsNull--;
                        mFemaleFbStudentVOList.remove(index);
                        for (int j = 0; j < mFbStudentVOList.size(); j++) {
                            if (divideclassClassVo.getId().equals(mFbStudentVOList.get(j).getId())) {
                                mFbStudentVOList.remove(j);
                                break;
                            }
                        }
                    }
                }
            }

            if (maleAndFemaleNotNull != 0) {
                for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                    DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                    int male = Integer.parseInt(divideclassClassVo.getBnum());
                    int female = Integer.parseInt(divideclassClassVo.getGnum());
                    if (male != 0 && female != 0) {
                        int index = rand.nextInt(maleAndFemaleNotNull);
                        DivideclassStudentVo divideclassStudentVo = mFbStudentVOList.get(index);
                        List<DivideclassStudentVo> fbStudentVOList = new ArrayList<>();
                        fbStudentVOList.add(divideclassStudentVo);
                        if (MALE.equals(divideclassStudentVo.getSex())) {
                            divideclassClassVo.setMaleList(fbStudentVOList);
                            int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                            int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                            float newAverageScore = (Float.parseFloat(divideclassClassVo.getAverage()) * (maleSize + femaleSize - 1) + Float.parseFloat(divideclassStudentVo.getTotalScore())) * 100 / (maleSize + femaleSize) / 100;
                            divideclassClassVo.setAverage(String.valueOf(newAverageScore));
                            maleAndFemaleNotNull--;
                            mFbStudentVOList.remove(index);
                            for (int j = 0; j < mMaleFbStudentVOList.size(); j++) {
                                if (divideclassStudentVo.getId().equals(mMaleFbStudentVOList.get(j).getId())) {
                                    mMaleFbStudentVOList.remove(j);
                                    break;
                                }
                            }
                        } else if (FEMALE.equals(divideclassStudentVo.getSex())) {
                            divideclassClassVo.setFemaleList(fbStudentVOList);
                            int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                            int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                            float newAverageScore = (Float.parseFloat(divideclassClassVo.getAverage()) * (maleSize + femaleSize - 1) + Float.parseFloat(divideclassStudentVo.getTotalScore())) * 100 / (maleSize + femaleSize) / 100;
                            divideclassClassVo.setAverage(String.valueOf(newAverageScore));
                            maleAndFemaleNotNull--;
                            mFbStudentVOList.remove(index);
                            for (int j = 0; j < mFemaleFbStudentVOList.size(); j++) {
                                if (divideclassStudentVo.getId().equals(mFemaleFbStudentVOList.get(j).getId())) {
                                    mFemaleFbStudentVOList.remove(j);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            List<DivideclassStudentVo> maleFbStudentVOList = new ArrayList<>();
            List<DivideclassStudentVo> femaleFbStudentVOList = new ArrayList<>();
            for (int i = 0; i < mFbStudentVOList.size(); i++) {
                DivideclassStudentVo divideclassStudentVo = mFbStudentVOList.get(i);
                if (MALE.equals(divideclassStudentVo.getSex())) {
                    maleFbStudentVOList.add(divideclassStudentVo);
                } else if (FEMALE.equals(mFbStudentVOList.get(i).getSex())) {
                    femaleFbStudentVOList.add(divideclassStudentVo);
                }
            }

            printLog();

            //剩下的学生随机分配
            int j = 0;
            for (int i = 0; i < mFbStudentVOList.size(); ) {
                for (; j < mFbClassDividingVOList.size(); ) {
                    int index;
                    List<DivideclassStudentVo> divideclassStudentVoList;
                    DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(j);
                    int male = Integer.parseInt(divideclassClassVo.getBnum());
                    int female = Integer.parseInt(divideclassClassVo.getGnum());
                    int maleListSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                    int femaleListSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                    if (male != maleListSize) {
                        index = getBestScore(divideclassClassVo, maleFbStudentVOList, averageScore);
                        if (divideclassClassVo.getMaleList() == null) {
                            divideclassStudentVoList = new ArrayList<>();
                        } else {
                            divideclassStudentVoList = divideclassClassVo.getMaleList();
                        }
                        divideclassStudentVoList.add(maleFbStudentVOList.get(index));
                        divideclassClassVo.setMaleList(divideclassStudentVoList);
                        int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                        int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                        float newAverageScore = (Float.parseFloat(divideclassClassVo.getAverage()) * (maleSize + femaleSize - 1) + Float.parseFloat(maleFbStudentVOList.get(index).getTotalScore())) * 100 / (maleSize + femaleSize) / 100;
                        divideclassClassVo.setAverage(String.valueOf(newAverageScore));
                        maleFbStudentVOList.remove(index);
                        j++;
                        i++;
                        printLog();
                        break;
                    } else if (female != femaleListSize) {
                        index = getBestScore(divideclassClassVo, femaleFbStudentVOList, averageScore);
                        if (divideclassClassVo.getFemaleList() == null) {
                            divideclassStudentVoList = new ArrayList<>();
                        } else {
                            divideclassStudentVoList = divideclassClassVo.getFemaleList();
                        }
                        divideclassStudentVoList.add(femaleFbStudentVOList.get(index));
                        divideclassClassVo.setFemaleList(divideclassStudentVoList);
                        int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                        int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                        float newAverageScore = (Float.parseFloat(divideclassClassVo.getAverage()) * (maleSize + femaleSize - 1) + Float.parseFloat(femaleFbStudentVOList.get(index).getTotalScore())) * 100 / (maleSize + femaleSize) / 100;
                        divideclassClassVo.setAverage(String.valueOf(newAverageScore));
                        femaleFbStudentVOList.remove(index);
                        j++;
                        i++;
                        printLog();
                        break;
                    } else {
                        j++;
                    }
                }
                if (j == mFbClassDividingVOList.size()) {
                    j = 0;
                }
            }

            //计算最高分班级和最低分班级误差,不符合学生换班
            boolean result = true;
            while (result) {
                endTime = System.currentTimeMillis();
                //System.out.println("正在分班,用时：" + ((endTime - startTime) / 1000 / 60) + "分" + ((endTime - startTime) / 1000 % 60) + "秒");
                if ((endTime - startTime) / 1000 / 60 > TIME) {
                    return false;
                }
                int minClassIndex = 0;
                int maxClassIndex = 0;
                float minScore = 0f;
                float maxScore = 0f;
                for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                    DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                    if (divideclassClassVo.getMaleList() != null) {
                        divideclassClassVo.setMaleList(sortFbStudentVOByScore(divideclassClassVo.getMaleList()));
                    }
                    if (divideclassClassVo.getFemaleList() != null) {
                        divideclassClassVo.setFemaleList(sortFbStudentVOByScore(divideclassClassVo.getFemaleList()));
                    }
                    float classAverage = Float.parseFloat(divideclassClassVo.getAverage());
                    if (i == 0) {
                        minScore = classAverage;
                        maxScore = classAverage;
                    } else {
                        if (classAverage < minScore) {
                            minClassIndex = i;
                            minScore = classAverage;
                        } else if (classAverage > maxScore) {
                            maxClassIndex = i;
                            maxScore = classAverage;
                        }
                    }
                }
                if (minClassIndex != maxClassIndex) {
                    if (Math.abs(maxScore - averageScore) <= mZfwc && Math.abs(averageScore - minScore) <= mZfwc) {
                        result = false;
                    } else {
                        changeStudent(maxClassIndex, minClassIndex);
                    }
                } else {
                    result = false;
                }
            }
        } else if (mCjjh) {
            boolean flag;
            int j;

            //按男生成绩排名循环
            flag = true;
            j = 0;
            for (int i = 0; i < mMaleFbStudentVOList.size(); ) {
                DivideclassStudentVo divideclassStudentVo = mMaleFbStudentVOList.get(i);
                if (flag) {
                    for (; j < mFbClassDividingVOList.size(); j++) {
                        DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(j);
                        int male = Integer.parseInt(divideclassClassVo.getBnum());
                        List<DivideclassStudentVo> divideclassStudentVoList = divideclassClassVo.getMaleList();
                        if (male != 0 && (divideclassStudentVoList == null || male != divideclassStudentVoList.size())) {
                            if (divideclassStudentVoList == null) {
                                divideclassStudentVoList = new ArrayList<>();
                            }
                            divideclassStudentVoList.add(divideclassStudentVo);
                            divideclassClassVo.setMaleList(divideclassStudentVoList);
                            j++;
                            i++;
                            break;
                        }
                    }
                    if (j == mFbClassDividingVOList.size()) {
                        flag = false;
                        j--;
                    }
                } else {
                    for (; j >= 0; j--) {
                        DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(j);
                        int male = Integer.parseInt(divideclassClassVo.getBnum());
                        List<DivideclassStudentVo> divideclassStudentVoList = divideclassClassVo.getMaleList();
                        if (male != 0 && (divideclassStudentVoList == null || male != divideclassStudentVoList.size())) {
                            if (divideclassStudentVoList == null) {
                                divideclassStudentVoList = new ArrayList<>();
                            }
                            divideclassStudentVoList.add(divideclassStudentVo);
                            divideclassClassVo.setMaleList(divideclassStudentVoList);
                            j--;
                            i++;
                            break;
                        }
                    }
                    if (j < 0) {
                        flag = true;
                        j++;
                    }
                }
            }

            //按女生成绩排名循环
            flag = true;
            j = mFbClassDividingVOList.size() - 1;
            for (int i = 0; i < mFemaleFbStudentVOList.size(); ) {
                DivideclassStudentVo divideclassStudentVo = mFemaleFbStudentVOList.get(i);
                if (flag) {
                    for (; j >= 0; ) {
                        DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(j);
                        int female = Integer.parseInt(divideclassClassVo.getGnum());
                        List<DivideclassStudentVo> divideclassStudentVoList = divideclassClassVo.getFemaleList();
                        if (female != 0 && (divideclassStudentVoList == null || female != divideclassStudentVoList.size())) {
                            if (divideclassStudentVoList == null) {
                                divideclassStudentVoList = new ArrayList<>();
                            }
                            divideclassStudentVoList.add(divideclassStudentVo);
                            divideclassClassVo.setFemaleList(divideclassStudentVoList);
                            j--;
                            i++;
                            break;
                        } else {
                            j--;
                        }
                    }
                    if (j < 0) {
                        flag = false;
                        j++;
                    }
                } else {
                    for (; j < mFbClassDividingVOList.size(); ) {
                        DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(j);
                        int female = Integer.parseInt(divideclassClassVo.getGnum());
                        List<DivideclassStudentVo> divideclassStudentVoList = divideclassClassVo.getFemaleList();
                        if (female != 0 && (divideclassStudentVoList == null || female != divideclassStudentVoList.size())) {
                            if (divideclassStudentVoList == null) {
                                divideclassStudentVoList = new ArrayList<>();
                            }
                            divideclassStudentVoList.add(divideclassStudentVo);
                            divideclassClassVo.setFemaleList(divideclassStudentVoList);
                            j++;
                            i++;
                            break;
                        } else {
                            j++;
                        }
                    }
                    if (j == mFbClassDividingVOList.size()) {
                        flag = true;
                        j--;
                    }
                }
            }
        } else if (mXbjh) {
            Random rand = new Random();
            for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                int male = Integer.parseInt(divideclassClassVo.getBnum());
                List<DivideclassStudentVo> maleList = new ArrayList<>();
                for (int j = 0; j < male; j++) {
                    int index = rand.nextInt(mMaleFbStudentVOList.size());
                    maleList.add(mMaleFbStudentVOList.get(index));
                    mMaleFbStudentVOList.remove(index);
                }
                divideclassClassVo.setMaleList(maleList);
                List<DivideclassStudentVo> femaleList = new ArrayList<>();
                int female = Integer.parseInt(divideclassClassVo.getGnum());
                for (int j = 0; j < female; j++) {
                    int index = rand.nextInt(mFemaleFbStudentVOList.size());
                    femaleList.add(mFemaleFbStudentVOList.get(index));
                    mFemaleFbStudentVOList.remove(index);
                }
                divideclassClassVo.setFemaleList(femaleList);
            }
        }
        return true;
    }

    private void printLog() {
        if (SHOWLOG) {
            for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
                DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
                int male = Integer.parseInt(divideclassClassVo.getBnum());
                int female = Integer.parseInt(divideclassClassVo.getGnum());
                int maleListSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
                int femaleListSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
                System.out.println(male + "\t" + female + "\t" + maleListSize + "\t" + femaleListSize);
            }
            System.out.println();
        }
    }

    private void changeStudent(int maxClassIndex, int minClassIndex) {
        DivideclassClassVo maxDivideclassClassVo = mFbClassDividingVOList.get(maxClassIndex);
        DivideclassClassVo minDivideclassClassVo = mFbClassDividingVOList.get(minClassIndex);
        List<DivideclassStudentVo> maxDivideclassStudentVoList = getFbStudentVOListForClass(maxDivideclassClassVo);
        List<DivideclassStudentVo> minDivideclassStudentVoList = getFbStudentVOListForClass(minDivideclassClassVo);
        int maxMale = Integer.parseInt(maxDivideclassClassVo.getBnum());
        int maxFemale = Integer.parseInt(maxDivideclassClassVo.getGnum());
        int minMale = Integer.parseInt(minDivideclassClassVo.getBnum());
        int minFemale = Integer.parseInt(minDivideclassClassVo.getGnum());

        //从高分班级随机一个非最高分学生
        int maxStudentIndex = new Random().nextInt(maxMale + maxFemale - 1) + 1;
        DivideclassStudentVo maxFbStudentVO = maxDivideclassStudentVoList.get(maxStudentIndex);
        int maxIndex = 0;
        if (MALE.equals(maxFbStudentVO.getSex())) {
            for (int i = 0; i < maxDivideclassClassVo.getMaleList().size(); i++) {
                if (maxFbStudentVO.getId().equals(maxDivideclassClassVo.getMaleList().get(i).getId())) {
                    maxIndex = i;
                    break;
                }
            }
        } else if (FEMALE.equals(maxFbStudentVO.getSex())) {
            for (int i = 0; i < maxDivideclassClassVo.getFemaleList().size(); i++) {
                if (maxFbStudentVO.getId().equals(maxDivideclassClassVo.getFemaleList().get(i).getId())) {
                    maxIndex = i;
                    break;
                }
            }
        }

        //从低分班级随机一个学生满足非最高分并且分数小于高分班级随机的学生分数
        int minIndex = 0;
        int minStartIndex;
        DivideclassStudentVo minFbStudentVO = null;
        float maxTotalScore = Float.parseFloat(maxFbStudentVO.getTotalScore());
        if (MALE.equals(maxFbStudentVO.getSex())) {
            if (minDivideclassClassVo.getMaleList() != null) {
                for (int i = 0; i < minDivideclassClassVo.getMaleList().size(); i++) {
                    String id = minDivideclassClassVo.getMaleList().get(i).getId();
                    float minTotalScore = Float.parseFloat(minDivideclassClassVo.getMaleList().get(i).getTotalScore());
                    if (maxTotalScore >= minTotalScore && (!id.equals(minDivideclassStudentVoList.get(0).getId()))) {
                        minStartIndex = i;
                        minIndex = new Random().nextInt(minDivideclassClassVo.getMaleList().size() - minStartIndex) + minStartIndex;
                        minFbStudentVO = minDivideclassClassVo.getMaleList().get(minIndex);
                        break;
                    }
                }
            }
        } else if (FEMALE.equals(maxFbStudentVO.getSex())) {
            if (minDivideclassClassVo.getFemaleList() != null) {
                for (int i = 0; i < minDivideclassClassVo.getFemaleList().size(); i++) {
                    String id = minDivideclassClassVo.getFemaleList().get(i).getId();
                    float minTotalScore = Float.parseFloat(minDivideclassClassVo.getFemaleList().get(i).getTotalScore());
                    if (maxTotalScore >= minTotalScore && (!id.equals(minDivideclassStudentVoList.get(0).getId()))) {
                        minStartIndex = i;
                        minIndex = new Random().nextInt(minDivideclassClassVo.getFemaleList().size() - minStartIndex) + minStartIndex;
                        minFbStudentVO = minDivideclassClassVo.getFemaleList().get(minIndex);
                        break;
                    }
                }
            }
        }

        //交换
        if (minFbStudentVO != null) {
            if (MALE.equals(maxFbStudentVO.getSex())) {
                maxDivideclassClassVo.getMaleList().remove(maxIndex);
                maxDivideclassClassVo.getMaleList().add(minFbStudentVO);
                float maxScore = (Float.parseFloat(maxDivideclassClassVo.getAverage()) * (maxMale + maxFemale) - Float.parseFloat(maxFbStudentVO.getTotalScore()) + Float.parseFloat(minFbStudentVO.getTotalScore())) / (maxMale + maxFemale);
                maxDivideclassClassVo.setAverage(String.valueOf(maxScore));
                minDivideclassClassVo.getMaleList().remove(minIndex);
                minDivideclassClassVo.getMaleList().add(maxFbStudentVO);
                float minScore = (Float.parseFloat(minDivideclassClassVo.getAverage()) * (minMale + minFemale) - Float.parseFloat(minFbStudentVO.getTotalScore()) + Float.parseFloat(maxFbStudentVO.getTotalScore())) / (minMale + minFemale);
                minDivideclassClassVo.setAverage(String.valueOf(minScore));
            } else if (FEMALE.equals(maxFbStudentVO.getSex())) {
                maxDivideclassClassVo.getFemaleList().remove(maxIndex);
                maxDivideclassClassVo.getFemaleList().add(minFbStudentVO);
                float maxScore = (Float.parseFloat(maxDivideclassClassVo.getAverage()) * (maxMale + maxFemale) - Float.parseFloat(maxFbStudentVO.getTotalScore()) + Float.parseFloat(minFbStudentVO.getTotalScore())) / (maxMale + maxFemale);
                maxDivideclassClassVo.setAverage(String.valueOf(maxScore));
                minDivideclassClassVo.getFemaleList().remove(minIndex);
                minDivideclassClassVo.getFemaleList().add(maxFbStudentVO);
                float minScore = (Float.parseFloat(minDivideclassClassVo.getAverage()) * (minMale + minFemale) - Float.parseFloat(minFbStudentVO.getTotalScore()) + Float.parseFloat(maxFbStudentVO.getTotalScore())) / (minMale + minFemale);
                minDivideclassClassVo.setAverage(String.valueOf(minScore));
            }
        }
    }

    private List<DivideclassStudentVo> getFbStudentVOListForClass(DivideclassClassVo divideclassClassVo) {
        int male = Integer.parseInt(divideclassClassVo.getBnum());
        int female = Integer.parseInt(divideclassClassVo.getGnum());
        List<DivideclassStudentVo> divideclassStudentVoList = new ArrayList<>();
        if (divideclassClassVo.getMaleList() != null) {
            for (int i = 0; i < male; i++) {
                divideclassStudentVoList.add(divideclassClassVo.getMaleList().get(i));
            }
        }
        if (divideclassClassVo.getFemaleList() != null) {
            for (int i = 0; i < female; i++) {
                divideclassStudentVoList.add(divideclassClassVo.getFemaleList().get(i));
            }
        }
        return sortFbStudentVOByScore(divideclassStudentVoList);
    }

    private int getBestScore(DivideclassClassVo divideclassClassVo, List<DivideclassStudentVo> divideclassStudentVoList, float averageScore) {
        int maleSize = divideclassClassVo.getMaleList() == null ? 0 : divideclassClassVo.getMaleList().size();
        int femaleSize = divideclassClassVo.getFemaleList() == null ? 0 : divideclassClassVo.getFemaleList().size();
        float score = Float.parseFloat(divideclassClassVo.getAverage());
        float bestScore = averageScore * (maleSize + femaleSize + 1) - score * (maleSize + femaleSize);

        int index = 0;
        float minScore = 0;
        for (int i = 0; i < divideclassStudentVoList.size(); i++) {
            DivideclassStudentVo divideclassStudentVo = divideclassStudentVoList.get(i);
            float totalScore = Float.parseFloat(divideclassStudentVo.getTotalScore());
            if (i == 0) {
                minScore = Math.abs(totalScore - bestScore);
                index = i;
            } else {
                if (Math.abs(totalScore - bestScore) < minScore) {
                    minScore = Math.abs(totalScore - bestScore);
                    index = i;
                }
            }
        }
        return index;
    }

    private void saveClassDividingResult(SysUser sysUser) {
        for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
            DivideclassClassVo divideclassClassVo = mFbClassDividingVOList.get(i);
            List<DivideclassStudentVo> list = new ArrayList<>();
            Integer total=0;
            if (divideclassClassVo.getMaleList() != null) {
                for (int j = 0; j < divideclassClassVo.getMaleList().size(); j++) {
                    DivideclassStudentVo fbStudentVO = divideclassClassVo.getMaleList().get(j);
                    fbStudentVO.setClassId(divideclassClassVo.getId());
                    if(StringUtils.isNotEmpty(divideclassClassVo.getMaleList().get(j).getTotalScore())){
                        total+=Integer.parseInt(divideclassClassVo.getMaleList().get(j).getTotalScore());
                    }else{
                        fbStudentVO.setTotalScore("0");
                    }
                    list.add(fbStudentVO);
                }
            }
            if (divideclassClassVo.getFemaleList() != null) {
                for (int j = 0; j < divideclassClassVo.getFemaleList().size(); j++) {
                    DivideclassStudentVo fbStudentVO = divideclassClassVo.getFemaleList().get(j);
                    fbStudentVO.setClassId(divideclassClassVo.getId());
                    if(StringUtils.isNotEmpty(divideclassClassVo.getFemaleList().get(j).getTotalScore())){
                        total+=Integer.parseInt(divideclassClassVo.getFemaleList().get(j).getTotalScore());
                    }else{
                        fbStudentVO.setTotalScore("0");
                    }
                    list.add(fbStudentVO);
                }
            }
            List<DivideclassStudentVo> fbStudentVOList = sortFbStudentVOByScore(list);
            //更新学生信息
            for (int j = 0; j < fbStudentVOList.size(); j++) {
                DivideclassStudentVo fbStudentVO = fbStudentVOList.get(j);
                DivideclassStudent fbStudent = new DivideclassStudent();
                EntryUtils.copyProperties(fbStudentVO, fbStudent);
                fbStudent.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                divideclassStudentDao.updateByPrimaryKey(fbStudent);
            }
            //更新班级信息
            DivideclassClass divideclassClass=divideclassClassDao.selectByPrimaryKey(divideclassClassVo.getId());
            divideclassClass.setBnum(divideclassClassVo.getMaleList().size()+"");
            divideclassClass.setGnum(divideclassClassVo.getFemaleList().size()+"");
            if(divideclassClassVo.getAverage().equals("0")){
                float average=(total/(divideclassClassVo.getMaleList().size()+divideclassClassVo.getFemaleList().size()));
                divideclassClass.setAverage(average+"");
            }else{
                divideclassClass.setAverage(divideclassClassVo.getAverage());
            }
            divideclassClassDao.updateByPrimaryKey(divideclassClass);
        }
    }

    private List<DivideclassStudentVo> sortFbStudentVOByScore(List<DivideclassStudentVo> list) {
        Collections.sort(list, new Comparator<DivideclassStudentVo>() {
            @Override
            public int compare(DivideclassStudentVo o1, DivideclassStudentVo o2) {
                if (Float.parseFloat(o1.getTotalScore()) > Float.parseFloat(o2.getTotalScore())) {
                    return -1;
                } else if (Float.parseFloat(o1.getTotalScore()) == Float.parseFloat(o2.getTotalScore())) {
                    return 0;
                } else {
                    return 1;
                }
            }
        });
        return list;
    }

    private ReturnResult prepareData(String divideId) {
        //分班基础信息
        Divideclass divideclass = divideclassDao.selectByPrimaryKey(divideId);
        mMaleFbStudentVOList = new ArrayList<>();//待分班男学生信息
        mFemaleFbStudentVOList = new ArrayList<>();//待分班女学生信息
        DivideclassStudentVo divideclassStudentVo = new DivideclassStudentVo();
        divideclassStudentVo.setDivideId(divideclass.getId());
        //查询此次分班下的所有学生
        mFbStudentVOList = divideclassStudentDao.getDivideclassStudent(divideclassStudentVo);
        for (int i = 0; i < mFbStudentVOList.size(); i++) {
            DivideclassStudentVo fbStudentVO = mFbStudentVOList.get(i);
            if (MALE.equals(fbStudentVO.getSex())) {
                mMaleFbStudentVOList.add(fbStudentVO);
            } else if (FEMALE.equals(mFbStudentVOList.get(i).getSex())) {
                mFemaleFbStudentVOList.add(fbStudentVO);
            }
        }
        //分班规则信息
        DivideclassRuleVo divideclassRuleVo = new DivideclassRuleVo();
        divideclassRuleVo.setDivideId(divideclass.getId());
        List<DivideclassRule> divideclassRuleList=divideclassRuleService.listExample(divideclassRuleVo);
        DivideclassRule divideclassRule = divideclassRuleList.get(0);
        mStudentNum = Integer.parseInt(divideclass.getDivideNum());//获取分班学生数量
        mXbjh = Integer.parseInt(divideclassRule.getIsSex()) == 1 ? true : false;//性别均衡
        mCjjh = Integer.parseInt(divideclassRule.getIsRank()) == 1 ? true : false;//成绩排名均衡
        mZfjh = Integer.parseInt(divideclassRule.getIsScore()) == 1 ? true : false;//总分均衡
        if (mZfjh) {
            mZfwc = Float.parseFloat(divideclassRule.getTotalError());//总分误差
        }
        //分班班级信息
        mFbClassDividingVOList = new ArrayList<>();
        DivideclassClassVo divideclassClassVo = new DivideclassClassVo();
        divideclassClassVo.setDivideId(divideId);
        List<DivideclassClass> fbClassVOList = divideclassClassDao.getDivideclassClassList(divideclassClassVo);
        for (int i = 0; i < fbClassVOList.size(); i++) {
            DivideclassClass divideclassClass = fbClassVOList.get(i);
            DivideclassClassVo fbClassDividingVO = new DivideclassClassVo();
            fbClassDividingVO.setId(divideclassClass.getId());
            fbClassDividingVO.setNum(divideclassClass.getNum());
            fbClassDividingVO.setAverage("0");
            mFbClassDividingVOList.add(fbClassDividingVO);
        }
        //分班结果信息
        int maleSize = mMaleFbStudentVOList.size();
        int femaleSize = mFemaleFbStudentVOList.size();
        int mSize = 0;
        int fSize = 0;
        for (int i = 0; i < mFbClassDividingVOList.size(); i++) {
            DivideclassClassVo fbClassDividingVO = mFbClassDividingVOList.get(i);
            int male = (int) Math.floor(Integer.parseInt(fbClassDividingVO.getNum()) * maleSize / (maleSize + femaleSize));
            int female = (int) Math.floor(Integer.parseInt(fbClassDividingVO.getNum()) * femaleSize / (maleSize + femaleSize));
            fbClassDividingVO.setBnum(String.valueOf(male));
            fbClassDividingVO.setGnum(String.valueOf(female));
            mSize += male;
            fSize += female;
        }
        int j = 0;
        for (int i = mSize; i < maleSize; i++) {
            for (; j < mFbClassDividingVOList.size(); ) {
                DivideclassClassVo fbClassDividingVO = mFbClassDividingVOList.get(j);
                int studentNum = Integer.parseInt(fbClassDividingVO.getNum());
                int male = Integer.parseInt(fbClassDividingVO.getBnum());
                int female = Integer.parseInt(fbClassDividingVO.getGnum());
                if (studentNum != (male + female)) {
                    fbClassDividingVO.setBnum(String.valueOf(male + 1));
                    j++;
                    break;
                } else {
                    j++;
                }
            }
        }
        j = 0;
        for (int i = fSize; i < femaleSize; i++) {
            for (; j < mFbClassDividingVOList.size(); ) {
                DivideclassClassVo fbClassDividingVO = mFbClassDividingVOList.get(j);
                int studentNum = Integer.parseInt(fbClassDividingVO.getNum());
                int male = Integer.parseInt(fbClassDividingVO.getBnum());
                int female = Integer.parseInt(fbClassDividingVO.getGnum());
                if (studentNum != (male + female)) {
                    fbClassDividingVO.setGnum(String.valueOf(female + 1));
                    j++;
                    break;
                } else {
                    j++;
                }
            }
        }
        return new ReturnResult(ErrorCode.CODE_0,"");
    }

   /* *//**
     * 分班调整
     *
     * @param fbStudentDTO 传入参数对象
     * @param userInfo     用户信息
     * @return ResultDto
     * @author rong yuan
     * @date 2018-10-11 15:11:25
     *//*
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDto changeClass(FbStudentDTO fbStudentDTO, UserInfo userInfo) {
        if (userInfo.getStaff() != null) {
            FbStudent fbStudent = fbStudentDao.getFbStudentById(fbStudentDTO.getId());
            fbStudent.setFbClassId(fbStudentDTO.getFbClassId());
            fbStudent.setUpdater(userInfo.getStaff().getId());
            fbStudent.setUpdateTime(new Date());
            fbStudentDao.saveOrUpdateFbStudent(fbStudent);
            return ResultUtil.success("");
        }
        return ResultUtil.fail("");
    }*/
    /**
     * 根据条件逻辑删除
     *
     * @param divideclassVo 参数接受对象
     * @param sysUser 当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 13:54:04
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(DivideclassVo divideclassVo, SysUser sysUser) {
        //要修改的字段
        Divideclass divideclass = new Divideclass();
        divideclass.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        divideclass.setUpdator(sysUser.getId());
        divideclass.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(Divideclass.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(divideclassVo.getId())) {
            criteria.andIn("id", Arrays.asList(divideclassVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        divideclassDao.updateByExampleSelective(divideclass, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param divideclassVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 13:54:04
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(DivideclassVo divideclassVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(Divideclass.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(divideclassVo.getId())) {
            criteria.andIn("id", Arrays.asList(divideclassVo.getId().split(",")));
        }
        divideclassDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }
}